<template>
  <div>
    <!-- 在标签内添加$attrs可以渲染上未注册的属性(未用props注册的属性) 
    $attrs为组件标签内没有在组件内用props声明的属性-->
    <input
      type="text"
      class="myinput"
      @input="handleInp"
      @blur="handleChange"
      :class="{ success: status, error: !status }"
      v-bind="$attrs"
    />
    <!-- <span class="errmsg" v-if="isshow">{{ errmsg }}</span> -->
  </div>
</template>

<script>
import { Toast } from "vant";
export default {
  // 通过设置 inheritAttrs为false阻止根元素继承没有设置props属性的值
  inheritAttrs: false,
  // props: ["rules", "errmsg"],
  props: {
    rules: {
      type: RegExp,
    },
    errmsg: {
      type: String,
      default: "用户名或密码输入有误！",
    },
  },
  data() {
    return {
      status: true,
      isshow: false,
    };
  },
  methods: {
    handleInp(e) {
      this.$emit("input", e.target.value);
      // 输入正则并验证通过
      if (this.rules) {
        if (this.rules.test(e.target.value)) {
          this.status = true;
          // this.isshow = false;
        } else {
          this.status = false;
          // this.isshow = true;
        }
      }
    },
    handleChange() {
      if (!this.status)
        Toast.fail({
          message: this.errmsg,
          duration: 2000,
          position: "top",
        });
    },
  },
};
</script>

<style lang="less" scoped>
.myinput {
  width: 318 * 100vw/360;
  height: 60px;
  outline: none;
  border: none;
  border-bottom: 3px solid #ccc;
  font-size: 20px;
  line-height: 60px;
}
.success {
  border-bottom: 3px solid #0a0;
}
.error {
  border-bottom: 3px solid red;
}
.errmsg {
  color: red;
  display: block;
  margin-top: 2px;
}
</style>